package com.wangtao.test2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class MyServer {

    public static void main(String[] args) {
        EventLoopGroup bossGruop = new NioEventLoopGroup();
        EventLoopGroup workerGruop = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGruop, workerGruop).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new MyByteToLongDecoder2());
                            pipeline.addLast(new MyLongToByteEncoder());
                            pipeline.addLast(new MyServerHandler());
                        }
                    });

            ChannelFuture future = bootstrap.bind(7777).addListener(cf -> {
                if (cf.isSuccess()) {
                    System.out.println("服务端启动成功");
                } else {
                    System.out.println("服务端启动失败");
                }
            });

            future.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGruop.shutdownGracefully();
            workerGruop.shutdownGracefully();
        }

    }
}


